package com.zhang.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.zhang.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.functions.TimedOutPartialMatchHandler;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * @title: 跳出明细计算
 * @author: zhang
 * @date: 2022/3/6 20:30
 * 执行流程
 * --执行模拟日志的jar
 * --将生成的日志发送到Nginx进行负载均衡
 * --Nginx将请求转发给日志服务器
 * --日志采集服务器将日志发送到kafka的ods_base_log_2022主题中
 * --BaseLogApp从ods_base_log_2022主题中读取数据进行分流
 * --UserJumpDetailApp从kafka的dwd_page_log_2022主题中读取页面日志
 * --使用FlinkCEP对页面日志中过滤跳出行为
 * 定义pattern
 * 将pattern应用到流上
 * 从流中提取超时数据
 */
public class UserJumpDetailApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
        //TODO 2.检查点设置

/*        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(60*1000L);
        //设置重启策略 固定重启次数
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,1000L));
        //任务结束不删除检查点文件
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //设置两个ck之间最少间隔时间
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(1000L);
        //设置状态后端
        env.setStateBackend(new FsStateBackend("hdfs://hadoop102/flink/gmall-ck"));
        System.setProperty("HADOOP_USER_NAME", "zhang");*/

        //TODO 3.从kafka读取数据，对数据进行转换,分配时间戳和水位线
        String sourceTopic = "dwd_page_log_2022";
        String groupId = "dwm_uj_app";
        String sinkTopic = "dwm_user_jump_detail_2022";
        KeyedStream<JSONObject, String> kafkaDS = env
                .addSource(MyKafkaUtil.getKafkaSource(sourceTopic, groupId))
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        //水位线生成策略
                        WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
                                //提取时间戳
                                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                        return element.getLong("ts");
                                    }
                                })

                )
                .keyBy(json -> json.getJSONObject("common").getString("mid"));

        //TODO 4.使用Flink cep过滤用户跳出明细
        //4.1 定义pattern
        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("first")
                .where(new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        String lastPage = jsonObj.getJSONObject("page").getString("last_page_id");
                        //第一个条件：第一次访问last_page_id为null
                        return lastPage == null || lastPage.length() <= 0;
                    }
                })
                .next("second")
                .where(new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        String page = jsonObj.getJSONObject("page").getString("page_id");
                        //第二条件：在规定时间内访问了网站其他页面
                        return page != null && page.length() > 0;
                    }
                })
                .within(Time.seconds(10L));//第三个条件：在10秒范围之内
        //4.2 将pattern作用到流上
        PatternStream<JSONObject> patternStream = CEP.pattern(kafkaDS, pattern);
        //4.3 提取事件 FlinkCEP可以将超时数据放到侧输出流。
        OutputTag<JSONObject> timeOutTag = new OutputTag<JSONObject>("timeOut") {
        };
        SingleOutputStreamOperator<JSONObject> resultDS = patternStream.flatSelect(
                timeOutTag,
                new PatternFlatTimeoutFunction<JSONObject, JSONObject>() {
                    @Override
                    public void timeout(Map<String, List<JSONObject>> map, long l, Collector<JSONObject> collector) throws Exception {
                        //提取超时事件，跳出事件
                        List<JSONObject> match = map.get("first");
                        for (JSONObject jsonObject : match) {
                            //⚠️：虽然调用的是 collector.collect（）方法，但是其实是将超时数据放到参数一指定的侧输出流
                            collector.collect(jsonObject);
                        }
                    }
                },
                new PatternFlatSelectFunction<JSONObject, JSONObject>() {
                    //匹配数据（跳转）
                    @Override
                    public void flatSelect(Map<String, List<JSONObject>> map, Collector<JSONObject> collector) throws Exception {
                        //如果提取匹配数据，属于跳转数据。不用提取
                    }
                }
        );
        //TODO 5.提取侧输出流数据，将数据发送到kafka
        resultDS.getSideOutput(timeOutTag).print("ujd");
        resultDS
                .getSideOutput(timeOutTag)
                .map(JSONAware::toJSONString)
                .addSink(MyKafkaUtil.getKafkaSink(sinkTopic));

        //TODO 1.启动任务
        env.execute();
    }
}
